// 引入依赖
require('dotenv').config(); // 加载 .env 文件
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const multer = require('multer');
const path = require('path');
// 引入响应函数
const sendResponse = require('./utils/response');

// 引入路由
const userRoutes = require('./routes/userRoutes');
const authRoutes = require('./routes/authRoutes');
const menuRoutes = require('./routes/menuRoutes');
const roleRoutes = require('./routes/roleRoutes');
const categoryRoutes = require('./routes/product/categoryRoutes');
const brandRoutes = require('./routes/product/brandRoutes');
const categoryBrandRoutes = require('./routes/product/categoryBrandRoutes');
const attrRoutes = require('./routes/product/attrRoutes');
const spuRoutes = require('./routes/product/spuRoutes');
const skuRoutes = require('./routes/product/skuRoutes');
const uploadRoutes = require('./routes/uploadRoutes');

// 连接数据库
const sequelize = require('./config/db');
const defineAssociations = require('./models/associations');
const { send } = require('process');

// 定义模型关联
defineAssociations(sequelize); // 确保传入 sequelize 实例

// 创建 express 实例
const app = express();

// 配置跨域和 body-parser
app.use(cors());
app.use(bodyParser.json());
// app.use(bodyParser.json({ limit: '50mb' }));
// app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));

// 路由
// 用户管理
app.use('/admin/acl/user', userRoutes);
// 用户登录和权限
app.use('/admin/acl/index', authRoutes);
// 菜单管理
app.use('/admin/acl/permission', menuRoutes);
// 角色管理
app.use('/admin/acl/role', roleRoutes);
// 商品分类
app.use('/admin/product/baseCategory', categoryRoutes);
// 商品品牌
app.use('/admin/product/baseTrademark', brandRoutes);
// 分类品牌
app.use('/admin/product/baseCategoryBrand', categoryBrandRoutes);
// 属性管理
app.use('/admin/product/attr', attrRoutes)
// spu管理
app.use('/admin/product/spu', spuRoutes)
// sku管理
app.use('/admin/product/sku', skuRoutes)

// 文件上传
app.use('/admin/file/', uploadRoutes)

// 静态资源目录
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));

// 404 处理
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
  sendResponse(res, { code: 404, message: 'Route not found' });
});

// 全局错误捕获
app.use((err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    return sendResponse(res, { code: 500, message: '文件上传失败：' + err.message });
  }
  console.error(err.stack);
  sendResponse(res, {
    code: 500,
    message: err.message || 'Internal Server Error'
  });
});

// 启动服务
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
